package com.qingke.ocr.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.qingke.ocr.pojo.Model;
import com.qingke.ocr.pojo.OCRMessage;

@WebServlet("/send")
public class SendServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public SendServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(request.getSession().getAttribute("nick")==null){
			return ;
		}
		if(request.getSession().getAttribute("logged")==null||(Integer)request.getSession().getAttribute("logged")!=1){
			return ;
		}
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		ServletContext sc= getServletContext();
		if(sc.getAttribute("list")==null){
			return ;
		}
		if(sc.getAttribute("map")==null){
			sc.setAttribute("map",new HashMap<String,Long>());
		}
		@SuppressWarnings("unchecked")
		List<OCRMessage> list=(List<OCRMessage>)sc.getAttribute("list");
		@SuppressWarnings("unchecked")
		Map<String,Long> map=(Map<String,Long>)sc.getAttribute("map");
		
		long currentTime=System.currentTimeMillis();
		String nick=request.getParameter("nickname");
		
//		if(map.get(nick)==null){
//			return ;
//		}
		long lastTime=map.get(nick)==null?currentTime:map.get(nick);
		map.put(nick,currentTime);
		
		List<String> nicks=new ArrayList<>();
		List<OCRMessage> msgs=new ArrayList<>();
		for(OCRMessage o:list){
			if(lastTime>o.getTime())
				continue;
			msgs.add(o);
		}
		for(String str:map.keySet()){
			nicks.add(str);
		}
		
		Model model=new Model();
		model.setNicks(nicks);
		model.setMsgs(msgs);
		Gson gson=new Gson();
		String result=gson.toJson(model);
		
		response.getWriter().append(result);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
